package com.hcb.tonguetiphealth.widget.recommendhealth;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.Cate;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class RecommendHealthCateBuyWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "RecommendHealthCateBuyWidget";
	private String url= Global.URL + Global.servlet_recommendCateBuy;
	
	
	private Activity ctx;
	private Handler mHandler;
	private Button bt_line, bt_commit;
	private LinearLayout ll_back;
	private TextView tv_price, tv_priceTotal, tv_date;
	private EditText et_num, et_person, et_tel, et_remark;
	private Cate cate;
	private Calendar calendar;
	private SimpleDateFormat simpleDateFormat;
	private String date , person, tel,remark;
	private int num;
	
	public RecommendHealthCateBuyWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.recommend_health_buy_now, this); 
		cate = (Cate)ctx.getIntent().getSerializableExtra("cate");
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取酒水列表...");
					break;
				case MessageWhat.DIMISS_DIALOG:

					dismissMessageDialog();
					break;
				case MessageWhat.COMMIT_ING:
					showMessageDialog(ctx, "正在提交订单...");
					break;
				case MessageWhat.COMMIT_SUCCEED:
					dismissMessageDialog();
					showMessage(ctx, "订单提交成功");
					ctx.setContentView(new RecommendHealthCateInfoWidget(ctx));
					break;
				case MessageWhat.COMMIT_FAILD:
					dismissMessageDialog();
					showMessage(ctx, "订单提交失败");
					break;
				}
			}
		};
		
		bt_line = (Button)findViewById(R.id.recommend_health_cate_buy_consume_line);
		bt_commit = (Button)findViewById(R.id.recommend_health_cate_commit_buy_button);
		ll_back = (LinearLayout)findViewById(R.id.recommend_health_cate_buy_back_button);
		tv_price = (TextView)findViewById(R.id.recommend_health_cate_buy_price_textview); 
		tv_priceTotal = (TextView)findViewById(R.id.recommend_health_cate_buy_total_textview);
		tv_date = (TextView)findViewById(R.id.recommend_health_cate_buy_date_textview);
		et_num = (EditText)findViewById(R.id.recommend_health_cate_buy_num_edittext);
		et_person = (EditText)findViewById(R.id.recommend_health_cate_buy_person_edittext);
		et_tel = (EditText)findViewById(R.id.recommend_health_cate_buy_tel_edittext);
		et_remark = (EditText)findViewById(R.id.recommend_health_cate_buy_remark_edittext);
		bt_line.setOnClickListener(this);
		bt_commit.setOnClickListener(this);
		ll_back.setOnClickListener(this);
		tv_date.setOnClickListener(this);
		et_num.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if(s.length() > 2) {
					et_num.setText(s.subSequence(0, 2));
					et_num.setSelection(2);
				}
				num = StringUtils.parseInt(et_num.getText().toString());
		        cate.setNum(num);
		        tv_priceTotal.setText(StringUtils.parseFloat(cate.getPrice()) * num +"");
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s) {}
		});
		
		initData();
	}
	
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.recommend_health_cate_buy_date_textview:
			selectDate();
			break;
		case R.id.recommend_health_cate_buy_back_button:
			ctx.setContentView(new RecommendHealthCateInfoWidget(ctx));
			break;
		case R.id.recommend_health_cate_commit_buy_button:
			commitBuy();
			break;
		case R.id.recommend_health_cate_buy_consume_line:
			
			break;
		default:
			break;
		}
	}
	
	private void initData() {
		calendar = Calendar.getInstance();
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
		date = simpleDateFormat.format(calendar.getTime());
        tv_date.setText(date);
        tv_price.setText(cate.getPrice());
        num = StringUtils.parseInt(et_num.getText().toString());
        cate.setNum(num);
        tv_priceTotal.setText(StringUtils.parseFloat(cate.getPrice()) * num +"");
        et_person.setText(Global.user.getRealName());
        et_tel.setText(Global.user.getTel());
	}
	private void selectDate() {
		new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// TODO Auto-generated method stub
				Calendar c = Calendar.getInstance();
				c.set(Calendar.YEAR, year); 
            	c.set(Calendar.MONTH, monthOfYear); 
            	c.set(Calendar.DAY_OF_MONTH, dayOfMonth); 
            	if(c.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) {
            		showMessage(ctx, "请设置合法的时间");
            	} else {
            		calendar = c;
                	date = simpleDateFormat.format(calendar.getTime());
            		tv_date.setText(date);
            	}
			}
		}, 
				calendar.get(Calendar.YEAR), 
				calendar.get(Calendar.MONTH), 
				calendar.get(Calendar.DAY_OF_MONTH) 
                ).show();
	}
	private void commitBuy() {
		person = et_person.getText().toString();
		tel = et_tel.getText().toString();
		remark = et_remark.getText().toString();
		if(num < 1) {
			showMessage(ctx, "请填写购买数量");
			return;
		}
		if(StringUtils.isEmpty(person) || person.length()<2) {
			showMessage(ctx, "请填写联系人");
			return;
		}
		if(StringUtils.isEmpty(tel)) {
			showMessage(ctx, "请填写手机号码");
			return;
		} else if(!IsValidMobileNo(tel)) {
			showMessage(ctx, "请填写正确的手机号码");
			return;
		}
		if(StringUtils.isEmpty(remark)) {
			showMessage(ctx, "请填写备注说明");
			return;
		}
		mHandler.sendEmptyMessage(MessageWhat.COMMIT_ING);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
					params.add(new BasicNameValuePair("cateId", cate.getId()));
					params.add(new BasicNameValuePair("num", cate.getNum() +""));
					params.add(new BasicNameValuePair("date", date));
					params.add(new BasicNameValuePair("person", person));
					params.add(new BasicNameValuePair("tel", tel));
					params.add(new BasicNameValuePair("remark", remark));
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("downWine -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						if(Global.DEBUG) {
							System.out.println("------ 得到msg: " + count + ":" + msg);
						}
						
						mHandler.sendEmptyMessage(MessageWhat.COMMIT_SUCCEED);
					} else {
						mHandler.sendEmptyMessage(MessageWhat.COMMIT_FAILD);
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.COMMIT_FAILD);
				}
			}
		}.start();
	}
	
	@Override
	public void notifyAdapter() {
		
	}
}
